package logic
{
	import com.codezen.helper.Worker;
	import com.codezen.util.CUtils;
	
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.net.URLLoader;
	import flash.net.URLLoaderDataFormat;
	import flash.net.URLRequest;
	import flash.net.URLRequestMethod;
	import flash.net.URLVariables;
	
	import mx.controls.Alert;
	import mx.utils.ObjectUtil;
	
	import utils.serials.Episode;
	import utils.serials.Serial;

	/**
	 * 
	 * @author Light
	 * 
	 * Data loader class
	 */
	public class SerialsDataLoader extends Worker
	{
		// user login and pass
		private static var userLogin:String;
		private static var userPass:String;
		private static var sh:String; 
		
		// data loaders
		private var request:URLRequest;
		private var loader:URLLoader;
		
		// data vars
		private var lastEps:Vector.<Episode>;
		private var series:Vector.<Serial>;
		private var episodes:Vector.<Episode>;
		private var videoURL:String;
		
		/**
		 * 
		 * @param login
		 * @param pass
		 * 
		 * Constructor
		 */
		public function SerialsDataLoader(login:String, pass:String, shd:String)
		{
			// save login and pass
			userLogin = login;
			userPass = pass;
			
			// save quality
			sh = shd;
			
			// init vars
			// create urlrequest and urlloader
			request = new URLRequest();
			loader = new URLLoader();
			// set prefs, add error event listener 
			loader.dataFormat = URLLoaderDataFormat.TEXT;
			loader.addEventListener(IOErrorEvent.IO_ERROR, onRequestError);
			
			// try loggin in
			tryLogin();
		}
		
		/**
		 * Gets last eps 
		 * @return 
		 * 
		 */
		public function get lastEpisodes():Vector.<Episode>{
			return lastEps;
		}
		
		/**
		 * Gets series list 
		 * @return 
		 * 
		 */
		public function get seriesList():Vector.<Serial>{
			return series;
		}
		
		public function get episodesList():Vector.<Episode>{
			return episodes;
		}
		
		public function get videoLink():String{
			return videoURL;
		}
		
		/**
		 * Try loggin in 
		 * 
		 */
		private function tryLogin():void{
			// add event listener 
			loader.addEventListener(Event.COMPLETE, onLoginAttempt);
			
			// vars
			var variables:URLVariables = new URLVariables();
			variables.login = userLogin;
			variables.password = userPass;
			
			// from urlrequest and urlloader
			request.url = "http://ru"+sh+"d.tv/";
			request.data = variables;
			request.method = URLRequestMethod.POST;
			// load
			loader.load(request);
		}
		
		/**
		 * On login data recieve 
		 * @param e
		 * 
		 */
		private function onLoginAttempt(e:Event):void{
			// remove event listener
			loader.removeEventListener(Event.COMPLETE, onLoginAttempt);
			
			// create result XML
			var data:String = e.target.data;
			
			if(data.indexOf("login") < 0 && data.indexOf("password") < 0){
				// dispatch inited event
				dispatchEvent(new Event(Event.INIT));
				//requestData();
			}else{
				dispatchError("Логин или пароль введены неверно!");
			}
		}
		
		public function getNews():void{
			loader.addEventListener(Event.COMPLETE, onNewsLoad);
			
			// from urlrequest and urlloader
			request.url = "http://ru"+sh+"d.tv/ShowSeries/new/XML/";
			// load 
			loader.load(request);
		}
		
		private function onNewsLoad(e:Event):void{
			// remove event listener
			loader.removeEventListener(Event.COMPLETE, onNewsLoad);
			
			lastEps = new Vector.<Episode>();
			
			var data:XML = new XML(e.target.data);
			var list:XMLList = data.fp.children();
			
			var item:Object;
			var epitem:Object;
			var ep:Episode;
			
			// serial data
			var serial_id:String;
			var serial_title:String;
			var serial_orig:String;
			var serial_simg:String;
			var serial_bimg:String;
			var serial_info:String;
			var serial_mark:String;
			
			for each(item in list){
				serial_id = item.seriesinfo.item.id_series;
				serial_title = item.seriesinfo.item.title;
				serial_orig = item.seriesinfo.item.etitle;
				serial_simg = "http://ru"+sh+"d.tv/"+item.seriesinfo.item.fpimg;
				serial_bimg = "http://ru"+sh+"d.tv/"+item.seriesinfo.item.pimg;
				serial_info = item.seriesinfo.item.info;
				serial_mark = item.seriesinfo.item.mark;
				
				for each(epitem in item.item){
					// new
					ep = new Episode();
					// serial data
					ep.serial_id = serial_id;
					ep.serial_original = serial_orig;
					ep.serial_title = serial_title;
					ep.serial_info = serial_info;
					ep.serial_simg = serial_simg;
					ep.serial_bimg = serial_bimg;
					ep.serial_marker = serial_mark;
					// ep data
					ep.id = epitem.id_episodes;
					ep.season = epitem.snum;
					ep.num = epitem.vnum;
					ep.title = epitem.title;
					if( epitem.snum < 10 ){
						ep.image = "http://ru"+sh+"d.tv/sc/"+serial_mark+"/0"+epitem.snum+"-";//+item.enum+".jpg";
					}else{
						ep.image = "http://ru"+sh+"d.tv/sc/"+serial_mark+"/"+epitem.snum+"-";//+item.enum+".jpg";
					}
					if( epitem.enum < 10 ){
						ep.image += "0"+epitem.enum+".jpg";
					}else{
						ep.image += epitem.enum+".jpg";
					}
					ep.tmark = epitem.tmark;
					ep.sub = epitem.sub1;
					// push
					lastEps.push(ep);
				}
			}
			
			endLoad();
		}
		
		
		public function requestData():void{
			loader.addEventListener(Event.COMPLETE, onDataLoad);
			
			// from urlrequest and urlloader
			request.url = "http://ru"+sh+"d.tv/ShowSeries/all/XML/";
			// load
			loader.load(request);
		}
		
		private function onDataLoad(e:Event):void{
			// remove event listener
			loader.removeEventListener(Event.COMPLETE, onDataLoad);
			
			// create result XML
			var data:XML = new XML(e.target.data);
			var list:XMLList = data.fp.serieslist.children();
			
			//trace(data);
			
			// init 
			series = new Vector.<Serial>();
			
			// parse
			var s:Serial;
			var item:Object;
			for each(item in list){
				//create 
				s = new Serial();
				// data
				s.id = item.id_series;
				s.title = item.title;
				s.original = item.etitle;
				s.bimg = "http://ru"+sh+"d.tv/"+item.pimg;
				s.simg = "http://ru"+sh+"d.tv/"+item.fpimg;
				s.marker = item.mark;
				s.info = htmlUnescape(item.info);
				// add
				series.push(s);
			}
			
			// end set
			// clean
			list = null;
			s = null;
			item = null;
			data = null;
			
			// end
			endLoad();
		}
		
		/**
		 * Loads series data by ID 
		 * @param id
		 * 
		 */
		public function loadSeries(id:String):void{
			// add
			loader.addEventListener(Event.COMPLETE, onSeriesData);
			
			// from urlrequest and urlloader
			request.url = "http://ru"+sh+"d.tv/ShowEpisodes/"+id+"/XML/";
			// load
			loader.load(request);
		}
		
		
		/**
		 * Series data recieve callback 
		 * @param e
		 * 
		 */
		private function onSeriesData(e:Event):void{
			// remove event listener
			loader.removeEventListener(Event.COMPLETE, onSeriesData);
			
			episodes = new Vector.<Episode>();
			
			// create result XML
			var data:XML = new XML(e.target.data);
			
			var list:XMLList = data.series.season.children();
			
			// serial data
			var serial_id:String = data.series.id_series;
			var serial_title:String = data.series.title;
			var serial_orig:String = data.series.etitle;
			var serial_simg:String = "http://ru"+sh+"d.tv/"+data.series.fpimg;
			var serial_bimg:String = "http://ru"+sh+"d.tv/"+data.series.pimg;
			var serial_info:String = htmlUnescape(data.series.info);
			var serial_mark:String = data.series.mark;

			// parse
			var ep:Episode;
			var item:Object;
			for each(item in list){//[i].children()){
				// new
				ep = new Episode();
				// serial data
				ep.serial_id = serial_id;
				ep.serial_original = serial_orig;
				ep.serial_title = serial_title;
				ep.serial_info = serial_info;
				ep.serial_simg = serial_simg;
				ep.serial_bimg = serial_bimg;
				ep.serial_marker = serial_mark;
				// ep data
				ep.id = item.id_episodes;
				ep.season = item.snum;
				ep.num = item.vnum;
				ep.title = item.title;
				if( item.snum < 10 ){
					ep.image = "http://ru"+sh+"d.tv/sc/"+serial_mark+"/0"+item.snum+"-";//+item.enum+".jpg";
				}else{
					ep.image = "http://ru"+sh+"d.tv/sc/"+serial_mark+"/"+item.snum+"-";//+item.enum+".jpg";
				}
				if( item.enum < 10 ){
					ep.image += "0"+item.enum+".jpg";
				}else{
					ep.image += item.enum+".jpg";
				}
				ep.tmark = item.tmark;
				ep.sub = item.sub1;
				// push
				episodes.push(ep);
			}
				
			// clean
			data = null;
			list = null;
			serial_id = null;
			serial_title = null;
			serial_orig = null;
			serial_simg = null;
			serial_bimg = null;
			serial_info = null;
			ep = null;
			item = null;
			
			// end
			endLoad();
		}
		
		public function getVideoURL(id:String):void{
			// add
			loader.addEventListener(Event.COMPLETE, onVideoURLData);
			
			// from urlrequest and urlloader
			request.url = "http://ru"+sh+"d.tv/GetEpisodeLink/"+id+"/XML/";
			// load
			loader.load(request);
		}
		
		private function onVideoURLData(e:Event):void{
			// remove event listener
			loader.removeEventListener(Event.COMPLETE, onVideoURLData);
			
			// create result XML
			var data:XML = new XML(e.target.data);
			
			videoURL = "http://"+data.item.server+"/content/"+data.item.vurl;
			
			endLoad();
		}		
		
		private function onRequestError(e:Event):void{
			Alert.show(e.toString(),"Ошибка подключения!");
			//
		}
		
		
		private function htmlUnescape(str:String):String{
			return CUtils.convertHTMLEntities( CUtils.stripTags(str) );
		}
	}
}